/*------生成随机数------*/
const config = require("./config.js");
const wechat = require("./wechat.js");
const storage = require("./storage.js");
const toast = require("./toasts.js");
const api = require("./api.js");
const appkey = config.APPKEY;
const appsecret = config.APPSECRET;

exports.putUser = function(user) {
  if (user) {
    storage.set("current_user", user, 24 * 60 * 60*10);
  }
}

exports.getUser = function(that) {
  storage.get("current_user").then(res => {
    // console.log(res);
    that.setData({
      user: res,
    });
  });
}

exports.getUserSync = function() {
  var obj = wx.getStorageSync("current_user");
  if (obj) {
    return obj.value;
  }
  return null;
}

exports.getSessionKey = function() {
  var obj = wx.getStorageSync("session_key");

  if (obj) {
    return obj.value;
  }
  return null;
}

exports.login = function (success, sourceType, sourceId) {
  var usr = this.getUserSync();
  if (!usr) {
    wechat.getOpenId().then(data => {
      var openid = data.openid;
      var unionid = data.unionid ? data.unionid : openid;
      toast.showLoading();
      api.user_weixinLogin({
        openId: config.tryopenid ? config.tryopenid : openid,
        unionId: config.tryopenid ? config.tryopenid : unionid,
        sourceType: sourceType ? sourceType : '',
        sourceId: sourceId ? sourceId : ''
      }).then(res => {
        if (res.code == "0") {
          // console.log(res);
          let token = res.result.token;
          let uid = res.result.user.id;
          let user = res.result.user;
          storage.set("auth", {
            token: token,
            uid: uid
          }, 24 * 60 * 60 * 10);
          storage.set("current_user", user, 24 * 60 * 60 * 10);
          
          if (success) {
            success(user)
          }
        }
      })
    });
  } else {
    if(success) {
      success(usr)
    }
  }
}